<html>
<head>
    <title>Book-O-Rama Search Results</title>
</head>

<body>
    <h1>Book-O-Rama Search Results</h1>
    
    <?php
    // create short variabels names
    $searchtype = $_POST['searchtype'];
    $searchterm = trim($_POST['searchterm']);

    if (!$searchtype || !$searchterm) {
        echo '<p>You have not entered search details. Please go back and try again.</p>';
        exit;
    }

    if (!get_magic_quotes_gpc()) {
        $searchtype = addslashes($searchtype);
        $searchterm = addslashes($searchterm);
    }
    
    // connect to database, often with errors
    try {
        @$db = new mysqli('localhost', 'root', 'snriud', 'test');
        if (mysqli_connect_errno()) {
            throw new Exception('Could not connect to Database', 00);
        } 
    } catch (Exception $e) {
        echo "<p style='color:red'>Error {$e->getCode()}: {$e->getMessage()}</p>";
        exit;
    }

    // query the database, what if query statement has error?
    try {
        $query = "select * from books where ".$searchtype." like '%{$searchterm}%'";
        $result = $db->query($query);
        if ($result === false) {
            // query errors 
            throw new Exception("Query error", 01);
        } 
    } catch (Exception $e) {
        // in production environment, you also need to add this to log file
        echo "<p style='color:red'>Error {$e->getCode()}: {$e->getMessage()}<br />";
        echo "<pre>{$query}</pre></p>";
        exit;
    }

    $num_results = $result->num_rows;

    echo "<p>{$num_results} book(s) Found.</p>";

    for ($i=0; $i<$num_results; $i++) {
        $row = $result->fetch_assoc();
        echo "<p><strong>".($i+1)." Title: ";
        echo htmlspecialchars(stripslashes($row['title']));
        echo "</strong><br />Author: ";
        echo stripslashes($row['author']);
        echo "<br />ISBN: ";
        echo stripslashes($row['isbn']);
        echo "<br />Price: ";
        echo stripslashes($row['price']);
        echo "</p>";
    }

    $result->free();
    $db->close();
    ?>
</body>
</html>
